#!/bin/bash

# Slackware build script for par
# Written by slakmagik <email removed>
# Released under the WTFPL
# Now maintained by B. Watson <urchlay@slackware.uk>

# 20200622 bkw:
# - Update for v1.53 (after *19 years*)
# - Correctly rm the source dir from previous runs
# - Fix mode 0700 top-level source dir (it's annoying)
# - i486 => i586
# - various tweaks
# - add default_env patch (see below)

cd $(dirname $0) ; CWD=$(pwd)

PRGNAM=par
SRCNAM=Par
VERSION=${VERSION:-1.53.0}
BUILD=${BUILD:-1}
TAG=${TAG:-_SBo}
PKGTYPE=${PKGTYPE:-tgz}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i586 ;;
    arm*) ARCH=arm ;;
       *) ARCH=$( uname -m ) ;;
  esac
fi

if [ ! -z "${PRINT_PACKAGE_NAME}" ]; then
  echo "$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.$PKGTYPE"
  exit 0
fi

TMP=${TMP:-/tmp/SBo}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

if [ "$ARCH" = "i586" ]; then
  SLKCFLAGS="-O2 -march=i586 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC"
  LIBDIRSUFFIX="64"
else
  SLKCFLAGS="-O2"
  LIBDIRSUFFIX=""
fi

set -e

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $SRCNAM-$VERSION
tar xvf $CWD/$SRCNAM-$VERSION.tar.gz
cd $SRCNAM-$VERSION
chown -R root:root .
# please don't revert this to template:
chmod 755 .
chmod 644 *

# 20200622 bkw: the man page says to:
# $ export PARINIT="rTbgqR B=.,?'_A_a_@ Q=_s>|"
# before running. This one-line patch just makes that the default, if
# the PARINIT variable isn't set. This sets a reasonable default so
# users don't have to diddle their startup files.
[ "${PRISTINE:-no}" = "no" ] && patch -p1 < $CWD/default_env.diff

make -f protoMakefile CFLAGS="$SLKCFLAGS"
mkdir -p $PKG/usr/bin
install -m0755 -s $PRGNAM $PKG/usr/bin

# rename ".doc" so nothing thinks it's a word document.
mv $PRGNAM.doc $PRGNAM.txt
sed -i "s/$PRGNAM\.doc/$PRGNAM.txt/g" $PRGNAM.txt $PRGNAM.1

mkdir -p $PKG/usr/man/man1
gzip -9c $PRGNAM.1 > $PKG/usr/man/man1/$PRGNAM.1.gz

PKGDOC=$PKG/usr/doc/$PRGNAM-$VERSION
mkdir -p $PKGDOC
cp -a $PRGNAM.txt releasenotes $PKGDOC
cat $CWD/$PRGNAM.SlackBuild > $PKGDOC/$PRGNAM.SlackBuild

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc

cd $PKG
/sbin/makepkg -l y -c n $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.$PKGTYPE
